<template>
  <div>
    <ListTab v-model="handleStatus" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="handleTabClick" />
    <div class="operator-manage">
      <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
        <div v-if="!showMobilePage" class="list-top">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
          <div v-if="hasRouteAuth(['auth:operator:edit', 'auth:operator:adminEdit'])" class="btn-right">
            <div class="create-button">
              <el-button
                type="primary"
                size="small"
                style="padding:8px 10px;"
                class="btn-operate"
                @click="toCreate('single')">
                添加新操作员
              </el-button>
            </div>
            <div class="create-button">
              <el-button
                type="primary"
                size="small"
                style="padding:8px 10px;"
                class="btn-operate"
                @click="toCreate('all')">
                批量创建操作员
              </el-button>
            </div>
          </div>
        </div>
        <div v-loading="listLoading" class="table-content">
          <u-table
            v-if="list && list.items && list.items.length > 0"
            ref="multipleTable"
            :data="list.items"
            :height="setTableHeight"
            :row-class-name="tableRowClassName"
            :row-height="49"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @selection-change="handleSelectionChange">
            <u-table-column
              type="selection"
              align="center"
              width="55"/>
            <u-table-column align="left" label="工号" width="100" prop="jobNumber" sortable>
              <template slot-scope="scope">
                {{ scope.row.jobNumber }}
              </template>
            </u-table-column>
            <u-table-column align="left" label="姓名" prop="operatorName" sortable>
              <template slot-scope="scope">
                <CheckUserInfo :user-id="scope.row.operatorId" :label="scope.row.operatorName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="已启用角色" prop="enabledRole" sortable min-width="120">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.enabledRole" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width:200px;">{{ scope.row.enabledRole }}</div>
                  <div class="ellipsisOne">{{ scope.row.enabledRole }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="已禁用角色" prop="notEnabledRole" sortable min-width="120">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.notEnabledRole" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width:200px;">{{ scope.row.notEnabledRole }}</div>
                  <div class="ellipsisOne">{{ scope.row.notEnabledRole }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="个人权限" prop="personAuth" sortable min-width="100">
              <template slot-scope="scope">
                {{ scope.row.personAuth?'已配置':'--' }}
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态" prop="status" sortable>
              <template slot-scope="scope">
                <span :class="!scope.row.status ? 'user-status-forbidden' : 'user-status-normal'">
                  {{ scope.row.status === 1?'启用':'禁用' }}
                </span>
              </template>
            </u-table-column>
            <u-table-column v-if="hasRouteAuth(['auth:operator:edit', 'auth:operator:adminEdit'])" align="left" label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="toEdit(scope.row)">编辑</el-button>
              </template>
            </u-table-column>
          </u-table>
          <empty-placeholder v-else style="margin-bottom: 24px" />
          <el-row v-if="showMobilePage" type="flex" justify="left">
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :small="true"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="pageLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </div>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <div style="margin-left: 0">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" />
              <el-dropdown v-if="showMobilePage" trigger="click">
                <el-button size="small" class="more-actions" style="margin: 0 24px 0 6px" >
                  操作<i v-if="!showMobilePage" class="el-icon-caret-top"/>
                </el-button>
                <el-dropdown-menu slot="dropdown" style="padding: 0;">
                  <el-dropdown-item style="text-align: center" @click.native="toCreate('single')">
                    <div>添加新操作员</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center" @click.native="toCreate('all')">
                    <div>批量创建操作员</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center" @click.native="changeStatus(1)">
                    <div>启用</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center" @click.native="changeStatus(0)">
                    <div>禁用</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center" @click.native="deleteItem">
                    <div style="color: red">删除</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-mobile-icon
              show-search-btn
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              v-if="hasRouteAuth(['auth:operator:edit', 'auth:operator:adminEdit'])"
              ref="btnGroupRef"
              :list="moreOperatorList"
              show-mobile-icon
            />
          </template>
          <template v-else>
            <div class="operator-box">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" />
              <el-button class="btn-item" @click="changeStatus(1)">启用</el-button>
              <el-button class="btn-item" @click="changeStatus(0)">禁用</el-button>
              <el-button class="btn-item" @click="deleteItem">删除</el-button>
            </div>
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="screenWidth < 1220 ? simplePageLayout:pageSizeLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { hasRouteAuth, ROUTER_TYPES } from '@/utils/permission';
import { roleList, operatorList, deleteOperator, changeOperatorStatus } from '@/api/auth';
import CreateButton from '@/components/CreateButton';
import ListTab from '@/components/ListTab';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import mobileTable from '@/mixins/mobileTable';
import { allAuth } from '@/components/AuthPage/authData';
import { mapState } from 'vuex';

export default {
  components: { CreateButton, ListTab, Title, EmptyPlaceholder, MoreOpeator },
  mixins: [TableAdaptive, tableSelections, mobileTable],
  data() {
    return {
      list: '',
      listLoading: false,
      isInit: true,
      perPage: 20,
      page: 1,
      handleStatus: 1,
      isIndeterminate: false,
      checkAll: false,
      roleList: { items: [] },
      selectionList: [],
      screenWidth: document.body.clientWidth,
      pageSizeLayout: 'total, prev, pager, next, sizes, jumper',
      simplePageLayout: 'total, prev, pager, next, jumper',
      isUmyTable: true,
      idKey: 'operatorId', // 多选框参数
      tableRefName: 'multipleTable',
      paramsObj: {
        authName: '',
        roleName: ''
      },
      allAuth
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 196 : 188;
    },
    tabList() {
      return [
        { id: 0, name: '角色管理', isHidden: hasRouteAuth(ROUTER_TYPES.AUTH_ROLE) },
        { id: 1, name: '操作员管理', isHidden: hasRouteAuth(ROUTER_TYPES.AUTH_OPERATOR) }
      ];
    },
    moreOperatorList() {
      return [
        { label: '添加新操作员', handelClick: () => this.toCreate('single') },
        { label: '批量创建操作员', handelClick: () => this.toCreate('all') }
      ];
    },
    filterList() {
      const arr = [
        { keyword: 'name', name: '姓名', labelWidth: '70px', type: 'input' },
        { keyword: 'roleName', name: '角色名称', labelWidth: '70px', type: 'input' },
        { keyword: 'authName', name: '权限名称', type: 'cascaderSelectWithChild', labelName: 'label', valueName: 'id',
          multiple: false, checkStrictly: false, showAllLevels: true, childrenVal: 'children', options: this.allAuth },
        { keyword: 'status', name: '状态', type: 'select', options: [{ value: 1, label: '启用' }, { value: 0, label: '禁用' }] }
      ];
      return arr;
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow) {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editOperator') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    if (hasRouteAuth([ROUTER_TYPES.AUTH_OPERATOR])) {
      next();
    } else if (hasRouteAuth([ROUTER_TYPES.AUTH_ROLE])) {
      next('/user/role');
    } else if (hasRouteAuth([ROUTER_TYPES.AUTH_LOG])) {
      next('/user/log');
    } else {
      next('/');
    }
  },
  activated() {
    this.handleStatus = 1;
    if (this.$route.query.roleName) {
      this.paramsObj.roleName = this.$route.query.roleName;
    }
    const roleItem = localStorage.getItem('_roleItem');
    if (roleItem) {
      // const obj = this.jsonParse(roleItem);
      localStorage.removeItem('_roleItem');
    }
    if (!this.$route.meta.isChange) {
      this.getLogList(true);
    } else {
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.getLogList(true);
      } else {
        const reset = localStorage.getItem('resetOperator') || false;
        this.getLogList(reset);
      }
    }
    this.getRole(1);
    localStorage.removeItem('resetOperator');
  },
  methods: {
    hasRouteAuth,
    handleTabClick(id) {
      id === 0 && this.$router.push({
        name: 'userAuthManage'
      });
    },
    queryClick() {
      this.getLogList(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.getLogList(true);
    },
    async getLogList(reset = false) {
      if (reset) this.page = 1;
      this.listLoading = true;
      const params = {
        page: this.page,
        perPage: this.perPage,
        ...this.paramsObj
      };
      /* if (this.searchName && this.searchName !== '') {
        params.name = this.searchName;
      } */
      operatorList(params).then(({ data }) => {
        this.list = data;
        if (data.items) {
          data.items.forEach(i => {
            if (i.role && i.role.length > 0) {
              const enabledRole = [];
              const notEnabledRole = [];
              const roleNames = [];
              i.role.forEach(r => {
                roleNames.push(r.roleName);
                if (r.status === 0) {
                  notEnabledRole.push(r.roleName);
                } else {
                  enabledRole.push(r.roleName);
                }
              });
              i.roleNames = roleNames.join(',');
              i.enabledRole = enabledRole.join(',');
              i.notEnabledRole = notEnabledRole.join(',');
            } else {
              i.enabledRole = '';
              i.notEnabledRole = '';
            }
          });
        }
        this.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    getRole(page = 1) {
      roleList(page, 10, { status: '' }).then(({ data }) => {
        if (page > 1 && this.roleList.items) {
          const concatList = this.roleList.items.concat(data.items);
          data.items = concatList;
          this.roleList = data;
        } else {
          this.roleList = data;
        }
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getLogList(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getLogList();
    },
    toEdit(data) {
      this.$router.push({
        name: 'editOperator',
        params: { operatorId: data.operatorId }
      });
    },
    toCreate(type) {
      this.$router.push({
        name: 'createOperator',
        query: { type: type }
      });
    },
    // 修改
    changeStatus(status) {
      const selectList = this.selectionList;
      if (selectList.length > 0) {
        const ids = selectList.map(item => item.operatorId);
        const params = {
          operatorIds: ids.join(','),
          status: status
        };
        changeOperatorStatus(params).then(res => {
          if (res.code) {
            this.$message({
              type: 'success',
              message: '修改成功'
            });
            this.getLogList();
          }
        });
      } else {
        this.$message.warning('请先进行选择');
      }
    },
    deleteItem() {
      const selectList = this.selectionList;
      const that = this;
      if (selectList.length > 0) {
        this.$confirm('此操作将永久删除这些记录, 是否继续?', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'del-message del-message-cancel',
          iconClass: 'del-icon',
          center: true
        }).then(() => {
          const ids = selectList.map(item => item.operatorId);
          const params = {
            ids: ids.join(',')
          };
          deleteOperator(params).then(res => {
            if (res.code) {
              that.$message({
                type: 'success',
                message: '删除成功'
              });
              that.getLogList(true);
            }
          });
        });
      } else {
        this.$message.warning('请先进行选择');
      }
    },
    // 选择
    handleCheckAllChange(value) {
      if (value) {
        this.list.items.forEach(row => {
          this.$refs['multipleTable'].toggleRowSelection([{ row, selected: true }], true);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.selectionList = val;
      const total = this.list.items.length;
      const checkedCount = val.length;
      this.checkAll = checkedCount === total;
      this.isIndeterminate = checkedCount > 0 && checkedCount < total;
    },
    jsonParse(str) {
      if (!str && str === '') return null;
      try {
        return JSON.parse(str);
      } catch (error) {
        return str;
      }
    },
    tableRowClassName({ row, rowIndex }) {
      const baseClass = 'pointer';
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[this.idKey]);
        return ids.includes(row[this.idKey]) ? `table-selected ${baseClass}` : baseClass;
      }
      return baseClass;
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.operator-manage {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .el-row {
      padding: 0;
    }
  }
  .list-top {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    .list-title {
      flex:1;
    }
    .btn-right{
      display: flex;
      .btn {
        margin-left: 10px;
      }
    }
  }
  .user-status-forbidden {
    color: red;
  }
  .user-status-normal {
    color: green
  }
  .operator-box {
    flex: 1;
    margin-left: 9px;
    display: flex;
    align-items: center;
    .btn-item {
      margin-left: 10px;
      padding: 5px 15px;
      font-size: 13px;
    }
  }
  & ::v-deep {
    th {
      .el-checkbox {
        display: none;
      }
    }
    .el-pagination__jump {
      margin-left: 0 !important;
    }
  }
}
.create-button {
  margin-left: 10px;
  .btn-create {
    // width: 100px;
    height: 30px;
    color: #fff !important;
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
</style>

